//
//  KeyboardLockView.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/24.
//

import SwiftUI
import TLCLock

struct KeyboardLockView: View {


    @State var count: String = "3"
    @State var lockTime: String = "1"

    let device: LockDevice

    var body: some View {
        VStack {
            YxrInputView("输错次数", text: $count)
            YxrInputView("锁定时长(分钟)", text: $lockTime)
            
            YxrConfirmView {
                onTapConfirm()
            }
            
            LogView()
            
        }.yxrNavigationTitle("键盘锁定策略")
    }

    func onTapConfirm() {
        guard let lockKey = Server.getSecret(device.macAddress) else {
            showToast("没有lockKey")
            return
        }

        guard let allowErrorNum = getValueFor(num: count), let minute = getValueFor(num: lockTime)
        else {
            showToast("请检查输入的内容是否正确")
            return
        }

        lockTask(desc: "键盘锁定策略") {
            await device.keyboardLock(
                allowErrorNum: allowErrorNum, lockMinute: minute, lockKey: lockKey, trackId: Server.testTrackId
            )
        }
    }

    func getValueFor(num: String) -> UInt8? {
        let num2 = num.trimmingCharacters(in: .whitespaces)
        if num2.isEmpty {
            return nil
        }
        guard var value = Int(num2) else {
            return nil
        }

        if value > 255 {
            value = 255
        } else if value < 0 {
            value = 0
        }

        return UInt8(value)
    }
}
